<?php

namespace App\Handlers;

use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Overtrue\Pinyin\Pinyin;

class TranslateBaiduHandler
{

    public function translate($text)
    {
        $http = new Client;


        $req_url = 'http://fanyi-api.baidu.com/api/trans/vip/translate?';

        $q = $text;
        $from = 'zh';
        $to = 'en';
        $appid = config("services.baidu_translate.appid");
        $key = config("services.baidu_translate.key");
        $salt = time();

        $sign = md5($appid.$q.$salt.$key);


        $query = http_build_query([
            'q' => $q,
            'from' => $from,
            'to' => $to,
            'appid' => $appid,
            'salt' => $salt,
            'sign' => $sign
        ]);


        $response = $http->get($req_url.$query);

        $result = json_decode($response->getBody(),true);

        if(isset($result['trans_result'][0]['dst'])){
            return Str::slug($result['trans_result'][0]['dst']);
        }else{
            return $this->pinyin($text);
        }

    }

    public function pinyin($text)
    {
        return Str::slug(app(Pinyin::class))->permalink($text);
    }
}
